from google.appengine.ext import db
from google.appengine.api import memcache
from domain import document
from repository import baserepository

class DocumentRepository(baserepository.BaseRepository):

    def __init__(self):
        self._has_next = False
        self._has_prev = False

    def hasNext(self):
        return self._has_next

    def hasPrev(self):
        return self._has_prev
    
    def getAll(self):
        documents = db.GqlQuery("SELECT * FROM Document ORDER BY date DESC")
        return documents

    def getAllByRange(self, page, items_per_page):
        query = db.GqlQuery("SELECT * FROM Document ORDER BY date DESC")
        documents = query.fetch(items_per_page, offset=(page * items_per_page))
        next = query.fetch(1, (page * items_per_page) + len(articles))
        if next:
            self._has_next = True
        if page > 0:
            self._has_prev = True
        return documents

    def getRange(self, page, items_per_page, category=None):
        if (category == None):
            query = db.GqlQuery("SELECT * FROM Document WHERE published=True ORDER BY date DESC")
        else:
            query = db.GqlQuery("SELECT * FROM Document WHERE published=True AND categories = :1 ORDER BY date DESC", category)
        documents = query.fetch(items_per_page, offset=(page * items_per_page))
        next = query.fetch(1, (page * items_per_page) + len(documents))
        if next:
            self._has_next = True
        if page > 0:
            self._has_prev = True
        return documents

    def getByKey(self, documentkey):
        return super(DocumentRepository, self).getByKey(documentkey, document.Document)

    def save(self, newdocument):
        return super(DocumentRepository, self).save(newdocument, document.Document)

    def delete(self, olddocument):
        super(DocumentRepository, self).delete(olddocument, document.Document)


